package com.nulgame.bukkit.plugin.cleaner;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.bukkit.entity.Player;

import com.nulgame.bukkit.plugin.logger.ASLogger;
import com.nulgame.bukkit.plugin.model.ChatInfo;

public class PlayerChatCleaner {
	private Set<Player> m_cleanedPlayer;
	private Map<Player, Map<String, ChatInfo>> m_recentPlayerChatMap;
	private long m_limitedTimeMillis;
	public PlayerChatCleaner(Set<Player> cleanedPlayer, Map<Player, Map<String, ChatInfo>> recentPlayerChatMap, Long limitedTimeMillis){
		m_cleanedPlayer = cleanedPlayer;
		m_recentPlayerChatMap = recentPlayerChatMap;
		m_limitedTimeMillis = limitedTimeMillis;
	}
	public void clean(){
		long currentTimeMillis = System.currentTimeMillis(); 
		for(Player player : m_cleanedPlayer){
			ASLogger.info("Clean up for player " + player.getName());
			Map<String, ChatInfo> chatInfoMap = m_recentPlayerChatMap.get(player);
			if(chatInfoMap != null){
				for(Entry<String, ChatInfo> chat : chatInfoMap.entrySet()){
					long beginTime = 0;
					synchronized (chat.getValue().beginTimeMillis) {
						beginTime = chat.getValue().beginTimeMillis;
					}
					if(currentTimeMillis - beginTime > m_limitedTimeMillis){
						chatInfoMap.remove(chat.getKey());
					}
				}
			}
			chatInfoMap = m_recentPlayerChatMap.get(player);
			if(chatInfoMap != null && chatInfoMap.isEmpty()){
				m_recentPlayerChatMap.remove(player);
				m_cleanedPlayer.remove(player);
			}
		}
	}
}
